package com.museum.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.museum.base.BaseApiService;
import com.museum.base.BaseResponse;
import com.museum.core.utils.JudgeInt;
import com.museum.entity.DO.Area;
import com.museum.entity.DO.AreaPermission;
import com.museum.entity.DO.Permission;
import com.museum.entity.DTO.Meta;
import com.museum.entity.DTO.permission.PermissionShow;
import com.museum.entity.DTO.area.addArea;
import com.museum.entity.DTO.area.queryArea;
import com.museum.mapper.AreaMapper;
import com.museum.mapper.AreaPermissionMapper;
import com.museum.mapper.PermissionMapper;
import com.museum.service.api.AreaServiceAPI;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LB
 * @version 1.0
 * @date 2020/12/20 10:27
 */
@Component
public class AreaServiceImpl extends BaseApiService<JSONObject>  implements AreaServiceAPI {
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private AreaPermissionMapper areaPermissionMapper;
    @Autowired
    private PermissionMapper permissionMapper;
  /**
   * @param
   * @Desciption 删除地域 根据地域编号
   * @return
   */
    @Override
    public BaseResponse<JSONObject> deleteAreaByNumber(Integer number) {
        Integer count =  areaMapper.selectCount(new QueryWrapper<Area>().eq("area_number",number));
        if(count==0){
            return setResult(201,"无此地域,请重试",null);
        }
        int areaId = areaMapper.selectIdByNumber(number);
        int result = areaMapper.selectCountById(areaId);
        Area area = areaMapper.selectById(areaId);
        if(result>0){
            //说明有子孩子
            return setResult(201,"请先删除其附属地域",null);
        }else{
            int i = areaMapper.deleteById(area);
            //删除权限
            List<Integer> ids = areaPermissionMapper.selectPermissionIds(number);
            areaPermissionMapper.deleteBatchIds(ids);
            return setResult(200,"删除成功",null);
        }
    }

    @Override
    public BaseResponse<JSONObject> getAllAreas() {
        JSONObject jsonObject = new JSONObject();
        //先获得树形的地区表
        List<Area> areaList = areaMapper.selectList(null);
        List<queryArea> areas = new ArrayList<>();
        int i=0;
        for (Area area : areaList) {
            queryArea queryArea = new queryArea();
            BeanUtils.copyProperties(area,queryArea);
            List<Integer> permissionIds =  areaPermissionMapper.selectPermissionIds(queryArea.getAreaNumber());
            //根据权限id 拿到所有权限实体
            List<Permission> permissionList = new ArrayList<>();
            for (Integer permissionId : permissionIds) {
                //System.out.println("权限类的id=="+permissionId);
                Permission permission = permissionMapper.selectOneByPermission(permissionId);
               //System.out.println("权限类是=="+permission+"次数"+i);
                if (permission != null)
                    permissionList.add(permission);
            }
//             i++;
//            for (Permission permission : permissionList) {
//                System.out.println("权限类=="+permission);
//            }
            //现在获得了permissionList数组
            List<PermissionShow> list = TransformPermissionShows(permissionList);
            List<PermissionShow> build = build2(list);
            queryArea.setPermissions(build);
            build =null;
            areas.add(queryArea);
        }
        //拥有了封装好的地域表了 进行树构建
        List<queryArea> buildTrees = build(areas);
        //丰富每一个地区的权限
        //根据地域拿到所有的权限 根据地区编号 拿到地区所有的权限 然后进行封装
        jsonObject.put("areaList",buildTrees);
        return setResultSuccess(jsonObject);
    }

    private List<PermissionShow> TransformPermissionShows(List<Permission> permissionList) {
        List<PermissionShow> permissionShows = new ArrayList<>();

        for (Permission permission : permissionList) {
            PermissionShow permissionShow = new PermissionShow();
            BeanUtils.copyProperties(permission, permissionShow);
            permissionShow.setMeta(new Meta(permission.getIcon(), permission.getName()));
            permissionShows.add(permissionShow);
        }
        return permissionShows;
    }

    public List<PermissionShow> build2(List<PermissionShow> treeNodes) {
        //创建list集合，用于数据最终封装
        List<PermissionShow> trees = new ArrayList<>();
        //把所有菜单list集合遍历，得到顶层菜单 pid=0菜单，设置level是1
        for (PermissionShow treeNode : treeNodes) {
            //得到顶层菜单 pid=0菜单
            if (treeNode.getParentId()==0) {
                //根据顶层菜单，向里面进行查询子菜单，封装到finalNode里面
                trees.add(findChildren2(treeNode, treeNodes));
            }
        }
        return trees;
    }

    private PermissionShow findChildren2(PermissionShow treeNode, List<PermissionShow> treeNodes) {
        //1 因为向一层菜单里面放二层菜单，二层里面还要放三层，把对象初始化
        treeNode.setChildren(new ArrayList<PermissionShow>());
        //2 遍历所有菜单list集合，进行判断比较，比较id和pid值是否相同
        for (PermissionShow node : treeNodes) {
            //判断 id和pid值是否相同
            if (treeNode.getPermissionId().equals(node.getParentId())) {

                //把查询出来的子菜单放到父菜单里面
                treeNode.getChildren().add(findChildren2(node, treeNodes));
            }
        }
        return treeNode;
    }

    private List<queryArea> build(List<queryArea> areas) {
        List<queryArea> list = new ArrayList<>();
        for (queryArea area : areas) {
            if(area.getParentId()==0){
                list.add(findChild(area,areas));
            }
        }
        return list;
    }

    private queryArea findChild(queryArea area, List<queryArea> areas) {
         area.setChildren(new ArrayList<queryArea>());
        for (queryArea queryArea : areas) {
             if(queryArea.getParentId().equals(area.getAreaId())){
                 area.getChildren().add(findChild(queryArea,areas));
             }
        }
         return  area;
    }

    /**
     * @param
     * @Desciption 添加地域
     * @return
     */
    @Transactional
    @Override
    public BaseResponse<JSONObject> addArea(addArea areaDTO) {
        String areaName = areaDTO.getAreaName();
        List<Area> areaList = areaMapper.selectList(null);
        for (Area area : areaList) {
            if(area.getAreaName().equals(areaName)){
                return setResult(201,"此地域已存在",null);
            }
        }
        //System.out.println("all-===="+areaDTO);
        //int parentId =  areaDTO.getParentId();
        String pId = String.valueOf(areaDTO.getParentId());
        //System.out.println("父id==="+pId);
        Area area = new Area();
        BeanUtils.copyProperties(areaDTO,area);
        //判断是否是子部门
       // if(pId!="null"){

        if(!JudgeInt.isInt(areaDTO.getParentId())){
            //没有父级部门的Id，默认是省级部门
            area.setParentId(Integer.parseInt(pId));
        }else{
            area.setParentId(0);
        }
        int insert = areaMapper.insert(area);
        //根据地域Number 分配地域所有的权限
        int areaNumber = area.getAreaNumber();
        List<Integer> ids = permissionMapper.selectPermissionIds();
        for(int i=0;i<ids.size();i++){
            AreaPermission ap = new AreaPermission();
            ap.setStatus(0);
            ap.setAreaNumber(area.getAreaNumber());
            ap.setPermissionId(ids.get(i));
            areaPermissionMapper.insert(ap);
        }
        if(insert>0){
            return setResult(200,"地域添加成功",null);
        }else{
            return setResult(201,"系统错误,请重试",null);
        }
    }
}

